<template>
  <div id="login">
    <div class="login-right">
      <div class="login-logo">
        <img src="@/assets/img/login/logo-hbdl.png" alt="logo" />
        <div>数字人业务情景培训系统</div>
      </div>
      <div class="label">账号</div>
      <div class="input">
        <input type="text" v-model="username" placeholder="请输入账号" />
      </div>
      <div class="label">密码</div>
      <div class="input">
        <input type="password" v-model="password" placeholder="请输入密码" @keyup.enter="handleLogin" />
      </div>
      <div v-if="isShowYzm == 'true'" class="yzm">
        <!-- <div class="label">验证码</div> -->
        <div class="input">
          <input type="text" v-model="code" placeholder="请输入验证码" @keyup.enter="handleLogin" />
        </div>
        <img v-if="captchaImage" :src="captchaImage" alt="验证码" @click="refreshCaptcha" />
      </div>
      <div class="btn" @click="handleLogin">登录</div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Login",
  data() {
    return {
      username: "", // 用户名
      password: "", // 密码
      code: "", // 验证码
      uuid: "", // 验证码标识符
      captchaImage: "", // 验证码图片
      captchaToken: "", // 验证码标识符
      errorMessage: "", // 错误提示信息
      isShowYzm: false, // 是否显示验证码
      userId: "", // 用户id
    };
  },
  created() {
    // const payload = { token: "test-token-12345" }; // 使用对象作为 payload
    // this.$store.dispatch("login", payload);
    // this.refreshCaptcha(); // 页面加载时初始化验证码
    //获取是否显示验证码
    // this.getisShowYzm();
  },
  methods: {
    getisShowYzm() {
      this.$axios
        .get("/system/config/4", { noToken: true }) // 使用 this.$axios 发起 GET 请求
        .then((response) => {
          this.isShowYzm = response.data.configValue;
          if (this.isShowYzm == "true") {
            this.refreshCaptcha();
          }
        });
    },
    refreshCaptcha() {
      this.$axios
        .get("/captchaImage", { noToken: true }) // 使用 this.$axios 发起 GET 请求
        .then((response) => {
          if (!response || !response.img || !response.uuid) {
            throw new Error("Invalid captcha response from server");
          }
          this.captchaImage = `data:image/png;base64,${response.img}`; // 验证码图片
          this.uuid = response.uuid; // 验证码标识符
        });
    },
    getUserInfo() {
      // const url = "/getInfo";/user/info
      const url = "/tes/user/info";
      this.$axios
        .get(url)
        .then((response) => {
          const res = response;
          if (res.code === 200) {
            this.userId = res.data.userId;
            localStorage.setItem("userInfo", JSON.stringify(res.data));
            const userInfo = JSON.parse(localStorage.getItem("userInfo"));

            // 建立WebSocket连接
            // this.initWebSocket();

            // 获取 redirect 参数
            const redirectPath = this.$route.query.redirect || "/";
            console.log("Redirecting to:", redirectPath);

            // 跳转到目标页面
            // this.$router.push(redirectPath);
            this.$router.push("/");
          }
        })
        .catch((error) => { });
    },

    // 初始化WebSocket连接
    initWebSocket() {
      if (this.userId && this.$websocket) {
        // 构建WebSocket URL
        const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
        const host = window.location.host;
        const websocketUrl = `${protocol}//192.168.1.165:10002/tes/ws/assess/150`;

        console.log("初始化WebSocket连接:", websocketUrl);

        // 更新WebSocket URL并重新连接
        this.$websocket.updateUrl(websocketUrl);

        // 关闭现有连接（如果有的话）
        if (this.$websocket.state.manager.socket) {
          this.$websocket.close();
        }

        // 建立新连接
        this.$websocket.connect();

        // 监听连接状态
        this.$websocket.on("open", () => {
          console.log("WebSocket连接成功");
        });

        this.$websocket.on("error", (error) => {
          console.error("WebSocket连接错误:", error);
        });

        this.$websocket.on("message", (data) => {
          console.log("收到WebSocket消息:", data);
        });
      } else {
        console.error("无法初始化WebSocket: userId或$websocket不可用");
      }
    },
    async handleLogin() {
      // 检查用户名和密码是否为空
      if (!this.username || !this.password) {
        this.$message.error("用户名和密码不能为空");
        return;
      }

      try {
        // const url = "/login";/tes/unauthorized/form
        const url = "/tes/unauthorized/form";
        const data = {
          username: this.username,
          password: this.password,
          // code: this.code, // 验证码
          // uuid: this.uuid, // 验证码标识符
        };

        // 使用 this.$axios 发起 POST 请求
        const response = await this.$axios.post(
          `/tes/unauthorized/form?username=${this.username}&password=${this.password}`,
          {
            // headers: {
            //   "Content-Type": "application/json",
            // },
            // noToken: true, // 登录接口不需要 token
          }
        );

        const res = response; // 获取响应数据

        if (res.code === 200) {
          this.$message.success(res.msg || "登录成功");

          // 调用 Vuex 的 login 方法保存 Token 和用户信息
          // await this.$store.dispatch("login", {
          //   token: res.token,
          // });
          // 将 Token 存储到 localStorage
          // localStorage.setItem("token", res.token);
          this.getUserInfo(); // 获取用户信息
        } else if (res.code === 10001) {
          this.$message.error(res.msg || "登录失败，请重试");
          // this.getisShowYzm(); // 登录失败时刷新验证码
        }
      } catch (error) {
        // this.getisShowYzm(); // 登录失败时刷新验证码
      }
    },
  },
};
</script>

<style lang="scss">
@font-face {
  font-family: "MyCustomFont";
  src: url("/myfont/优设标题圆.TTF") format("truetype");
  font-weight: normal;
  font-style: normal;
}
</style>
<style lang="scss" scoped>
#login {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("@/assets/img/login/bg.png") no-repeat center center;
  background-size: cover;

  .login-left {
    position: relative;
    width: 747px;
    height: 630px;
    flex-shrink: 0;
    background: url("@/assets/img/login/left-3.png") no-repeat center center;

    .left-1 {
      position: absolute;
      top: 10px;
      left: 520px;
      animation: bounceai 2s ease-in-out infinite;
    }

    .left-2 {
      position: absolute;
      top: 320px;
      left: 400px;
      animation: bounceai 2s ease-in-out infinite 0.5s;
    }

    .left-txt {
      font-family: "MyCustomFont";
      position: absolute;
      top: 133px;
      left: 60px;
      font-size: 48px;
      color: #155eef;
      // text-shadow: 1px 2px 18px rgba(255,255,255,0.78);
      background: linear-gradient(45deg,
          rgba(255, 255, 255, 0) 40%,
          rgba(255, 255, 255, 0.7),
          rgba(255, 255, 255, 0) 60%) -100% / 50% no-repeat currentColor;
      -webkit-text-fill-color: transparent;
      -webkit-background-clip: text;
      background-clip: text;
      animation: sharktxt 4s infinite;
    }

    @keyframes sharktxt {
      0% {
        background-position: -100%;
      }

      50% {
        /* 原始动画持续时间为2秒，因此在这里插入 */
        background-position: 200%;
      }

      50.1%,
      100% {
        /* 在50.1%到100%之间保持原样，即产生2秒的延迟 */
        background-position: 200%;
      }
    }

    @keyframes bounceai {

      0%,
      100% {
        /* 开始和结束位置 */
        transform: translateY(0px);
      }

      50% {
        /* 中间点位置 */
        transform: translateY(-10px);
      }
    }
  }

  .login-right {
    width: 470px;
    flex-shrink: 0;
    background: rgba(255, 255, 255, 0.7);
    box-shadow: 0px 7px 7px 0px rgba(136, 156, 187, 0.36);
    border-radius: 20px;
    border: 1px solid #ffffff;
    padding: 100px 45px;
    box-sizing: border-box;

    .login-logo {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
      height: 56px;
      text-align: center;
      margin-bottom: 42px;

      img {
        height: 100%;
      }

      div {
        font-weight: bold;
        font-size: 23px;
        color: #1D2939;
      }
    }

    .label {
      font-size: 14px;
      color: #262e3e;
      margin-bottom: 10px;
    }

    .input {
      margin-bottom: 22px;

      input {
        width: 100%;
        height: 40px;
        background: #ffffff;
        border-radius: 10px;
        outline: none;
        border: 0;
        box-sizing: border-box;
        padding: 0 20px;
        font-size: 14px;
      }
    }

    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 49px;
      background: #155eef;
      border-radius: 10px;
      font-size: 16px;
      color: #ffffff;
      margin-top: 44px;
      cursor: pointer;

      &:hover {
        background: #1350c8;
      }
    }

    .yzm {
      display: flex;
      align-items: center;
      gap: 10px;

      .label {
        min-width: 50px;
        margin-bottom: 0;
      }

      .input {
        width: 100%;
        margin-bottom: 0;
      }

      img {
        height: 40px;
        transition: all 0.3s ease;
      }
    }
  }
}
</style>